import 'base_model.dart';

class ChatMessage implements BaseModel {
  final int? id;
  final int chatRoomId;
  final int senderId;
  final String content;
  final DateTime createdAt;
  final String readBy; // 已读用户ID，用逗号分隔

  ChatMessage({
    this.id,
    required this.chatRoomId,
    required this.senderId,
    required this.content,
    required this.createdAt,
    this.readBy = '',
  });

  @override
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'chat_room_id': chatRoomId,
      'sender_id': senderId,
      'content': content,
      'created_at': createdAt.millisecondsSinceEpoch,
      'read_by': readBy,
    };
  }

  factory ChatMessage.fromJson(Map<String, dynamic> json) {
    return ChatMessage(
      id: json['id'],
      chatRoomId: json['chat_room_id'],
      senderId: json['sender_id'],
      content: json['content'] ?? '',
      createdAt: DateTime.fromMillisecondsSinceEpoch(json['created_at']),
      readBy: json['read_by'] ?? '',
    );
  }

  // 检查用户是否已读此消息
  bool isReadBy(int userId) {
    if (readBy.isEmpty) return false;
    final readByList = readBy.split(',').map((id) => int.parse(id)).toList();
    return readByList.contains(userId);
  }

  // 获取已读用户ID列表
  List<int> get readByList {
    if (readBy.isEmpty) return [];
    return readBy
        .split(',')
        .where((id) => id.isNotEmpty)
        .map((id) => int.parse(id))
        .toList();
  }

  // 标记为用户已读
  ChatMessage markAsRead(int userId) {
    if (isReadBy(userId)) return this;

    final List<int> newReadByList = List.from(readByList);
    newReadByList.add(userId);
    final newReadBy = newReadByList.join(',');

    return ChatMessage(
      id: id,
      chatRoomId: chatRoomId,
      senderId: senderId,
      content: content,
      createdAt: createdAt,
      readBy: newReadBy,
    );
  }

  // 复制对象并修改指定字段
  ChatMessage copyWith({
    int? id,
    int? chatRoomId,
    int? senderId,
    String? content,
    DateTime? createdAt,
    String? readBy,
  }) {
    return ChatMessage(
      id: id ?? this.id,
      chatRoomId: chatRoomId ?? this.chatRoomId,
      senderId: senderId ?? this.senderId,
      content: content ?? this.content,
      createdAt: createdAt ?? this.createdAt,
      readBy: readBy ?? this.readBy,
    );
  }
}
